/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package whr.modules.sys.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import whr.common.utils.MapUtils;
import whr.modules.sys.dao.SysRoleDao;
import whr.modules.sys.dao.SysUserDao;
import whr.modules.sys.dao.SysUserRoleDao;
import whr.modules.sys.entity.SysUserEntity;
import whr.modules.sys.entity.SysUserRoleEntity;
import whr.modules.sys.service.SysUserRoleService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;



/**
 * 用户与角色对应关系
 *
 * @author Mark sunlightcs@gmail.com
 */
@Service("sysUserRoleService")
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleDao, SysUserRoleEntity> implements SysUserRoleService {

	@Autowired
	private SysRoleDao sysRoleDao;

	@Autowired
	private SysUserRoleDao SysUserRoleDao;

	@Autowired
	private SysUserDao sysUserDao;

	@Override
	public void saveOrUpdate(Long userId, List<Long> roleIdList) {
		//先删除用户与角色关系
		this.removeByMap(new MapUtils().put("user_id", userId));

		if(roleIdList == null || roleIdList.size() == 0){
			return ;
		}

		//保存用户与角色关系
		for(Long roleId : roleIdList){
			SysUserRoleEntity sysUserRoleEntity = new SysUserRoleEntity();
			sysUserRoleEntity.setUserId(userId);
			sysUserRoleEntity.setRoleId(roleId);

			this.save(sysUserRoleEntity);
		}
	}

	@Override
	public List<Long> queryRoleIdList(Long userId) {
		return baseMapper.queryRoleIdList(userId);
	}

	@Override
	public int deleteBatch(Long[] roleIds){
		return baseMapper.deleteBatch(roleIds);
	}

	/*
	 * 查询角色为面试官的用户集合
	 * */
	@Override
	public List<SysUserEntity> queryInterviewer() {

		// 获取面试官的角色id
		Long interviewId = sysRoleDao.getInterviewreId("面试官");

		// 根据角色id获取所有用户id
		List<Long> userId = SysUserRoleDao.queryUserId(interviewId);

		// 根据用户id获取所有面试者的姓名
		ArrayList<SysUserEntity> list = new ArrayList<>();

		for (Long id : userId) {
			SysUserEntity sysUserEntity = new SysUserEntity();
			sysUserEntity.setUserId(id);
			String username = sysUserDao.queryInterviewer(id);
			sysUserEntity.setUsername(username);
			list.add(sysUserEntity);
		}

		return list;

	}


}
